package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.ChineseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: recruit-boot-parent
 *
 * @author: JD
 * @create: 2020-08-28 10:28
 **/
@RestController
@RequestMapping("/sys/order/list")
public class SysDeptAndUserController {

    @Autowired
    ISysDepartService departService;

    @Autowired
    ISysUserService userService;

    @Autowired
    ISysBaseAPI baseAPI;

    @GetMapping("/dept")
    public Result<Map<String, List<SysDepart>>> getDepartOrderList() throws InvocationTargetException, BadHanyuPinyinOutputFormatCombination, IllegalAccessException, NoSuchMethodException {
        LambdaQueryWrapper<SysDepart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDepart::getDelFlag, false).isNotNull(SysDepart::getParentId);
        List<SysDepart> departs = departService.list(queryWrapper);
        Map<String, List<SysDepart>> map = new ChineseUtil<SysDepart>().getUserCodeGroup(departs, "getDepartName");
        return Result.ok(map);
    }

    @GetMapping("/user")
    public Result<Map<String, List<SysUser>>> getUserOrderList() throws InvocationTargetException, BadHanyuPinyinOutputFormatCombination, IllegalAccessException, NoSuchMethodException {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDelFlag, false);
        List<SysUser> sysUsers = userService.list(queryWrapper);
        List<String> userIds = sysUsers.stream().map(SysUser::getId).collect(Collectors.toList());
        Map<String, String> useDepNames = baseAPI.getDepNamesByUserIds(userIds);
        sysUsers.forEach(item -> {
            //TODO 临时借用这个字段用于页面展示
            item.setOrgCode(useDepNames.get(item.getId()));
        });
        Map<String, List<SysUser>> map = new ChineseUtil<SysUser>().getUserCodeGroup(sysUsers, "getRealname");
        return Result.ok(map);
    }
}
